<script setup lang="ts">
import { ref, computed } from 'vue'
import { ReloadOutlined } from '@ant-design/icons-vue';
import { GetReviewAssessment, GetQueryPersonalScore, PostSubmitAssessmenteMoloyee, GetQueryPersonalWorkPlan,PostauditAssessment } from '@/api/main'
import moment from 'moment';
import { message } from 'ant-design-vue';
import useUserStore from "@/stores/modules/user";
const userStore = useUserStore()
const dataSource = ref([])
const columns = [
    {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        slots: { customRender: 'index' },
        align:"center"
    },
    {
        title: '考核名称',
        dataIndex: 'name',
        key: 'name',
         align:"center"
    },
    {
        title: '姓名',
        dataIndex: 'empname',
        key: 'empname',
         align:"center"
    },
    {
        title: '创建时间',
        dataIndex: 'reportingMonth',
        key: 'reportingMonth',
         align:"center"
    },
    {
        title: '部门',
        dataIndex: 'orgName',
        key: 'orgName',
         align:"center"
    },
    {
        title: '当前评分',
        dataIndex: 'finalScore',
        key: 'finalScore',
        slots: { customRender: 'finalScore' },
         align:"center"
    },
    {
        title: '考核等级',
        dataIndex: 'assessmentGrade',
        key: 'assessmentGrade',
        slots: { customRender: 'assessmentGrade' },
         align:"center"
    },
    {
        title: '流程状态',
        dataIndex: 'status',
        key: 'status',
        slots: { customRender: 'status' },
         align:"center"
    },
    {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        slots: { customRender: 'action' },
         align:"center"
    },
]
const pagination = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
})
// pageSize 变化的回调
const onShowSizeChange = (current, size) => {
    pagination.value.pageNum = current
    pagination.value.pageSize = size
    getData()
}
const getData = () => {
    GetReviewAssessment({
        empId: userStore.empid,
        pageNum: pagination.value.pageNum,
        pageSize: pagination.value.pageSize,
        taskStatus: "wait"
    }).then((response: any) => {
        dataSource.value = response.data
        pagination.value.total = response.total
    })
}
getData()

// 计算属性，计算最高得分
const calculationMaxScore = computed(() => {
    return Object.values(personalScoreList.value).reduce((total, item) => {
        const childrenMaxScoreSum = item.children.reduce((acc, child) => acc + child.maxScore, 0);
        return total + childrenMaxScoreSum;
    }, 0);
});

// 计算属性，计算自评分
const calculationSelfRating = computed(() => {
    return Object.values(personalScoreList.value).reduce((total, item) => {
        const childrenMaxScoreSum = item.children.reduce((acc, child) => acc + child.selfRating, 0);
        return total + childrenMaxScoreSum;
    }, 0);
});
// 计算属性，部门评分
const calculationDepartmentRating = computed(() => {
    return Object.values(personalScoreList.value).reduce((total, item) => {
        const childrenMaxScoreSum = item.children.reduce((acc, child) => acc + child.departmentRating, 0);
        return total + childrenMaxScoreSum;
    }, 0);
});
// 计算属性，支部评分
const calculationBranchRating = computed(() => {
    return Object.values(personalScoreList.value).reduce((total, item) => {
        const childrenMaxScoreSum = item.children.reduce((acc, child) => acc + child.branchRating, 0);
        return total + childrenMaxScoreSum;
    }, 0);
});
// 计算属性，领导评分
const calculationSupervisorRating = computed(() => {
    return Object.values(personalScoreList.value).reduce((total, item) => {
        const childrenMaxScoreSum = item.children.reduce((acc, child) => acc + child.supervisorRating, 0);
        return total + childrenMaxScoreSum;
    }, 0);
});
// 抽屉
const visible = ref<boolean>(false);
const drawerRecord = ref(null)

const assessmentId = ref(null)
const afterVisibleChange = (bool: boolean) => {
    // console.log('visible', bool);
};
// 显示抽屉
const showDrawer = (record: any) => {
    drawerRecord.value = record
    assessmentId.value = record.id
    visible.value = true;
    GetQueryPersonalScoreList()

    getWordkPlan()
};

const personalScoreList = ref([]);
const GetQueryPersonalScoreList = () => {
    GetQueryPersonalScore(drawerRecord.value).then((response: any) => {
        const groupedData = {};
        // 把考核内容list 改为树形结构
        response.forEach(item => {
            if (!groupedData[item.contentType]) {
                groupedData[item.contentType] = {
                    contentType: item.contentType,
                    contentName: item.contentName,
                    children: []
                };
            }
            groupedData[item.contentType].children.push(item);
        });
        personalScoreList.value = groupedData || [];
    })
}
const workPlan = ref([])
// 新增计划
const handleAddWorkPlan = () => {
    workPlan.value.push({
        glid: drawerRecord.value.id,
        workPlanContent: "",
        plannedCompletionDate: "",
        remarks: ""
    })
}
// 删除计划
const handleDelWorkPlan = (index: number) => {
    workPlan.value.splice(index, 1)
}
// 保存草稿

// const employee = ref({
//     id: "",
//     jobTitle: "",// 职称
//     position: "",//岗位
//     duty: "",// 职务
//     workSummary: "",// 工作总结
//     remarks: "",//备注
//     rewardPunishmentScore: "",// 奖惩分数
//     rewardPunishmentReason: "",// 奖惩理由
//     status: '',// 流程状态

// })
// 获取工作计划
const getWordkPlan = () => {
    GetQueryPersonalWorkPlan({
        assessmentId: drawerRecord.value.id
    }).then((response => {
        workPlan.value = response.data
    }))
}
// 保存草稿
const handleSaveDraft = () => {
    workPlan.value.forEach(item => {
        item.plannedCompletionDate = moment(item.plannedCompletionDate).format('YYYY-MM-DD')
    })
    const scores = [];
    for (const key in personalScoreList.value) {
        if (personalScoreList.value.hasOwnProperty(key)) {
            const children = personalScoreList.value[key].children;
            if (children && children.length > 0) {
                scores.push(...children);
            }
        }
    }
    let params = {
        employee: drawerRecord.value,
        subStatus: 0, //状态
        workPlans: workPlan.value, //计划
        scores: scores //成绩
    }

    PostSubmitAssessmenteMoloyee(params).then(response => {
        if (response.code == 200) {
            message.success(response.msg)
            visible.value = false
        } else {
            message.error(response.msg)
        }
    })
}
// 提交
const handleSubmit = () => {
    workPlan.value.forEach(item => {
        item.plannedCompletionDate = moment(item.plannedCompletionDate).format('YYYY-MM-DD')
    })
    const scores = [];
    for (const key in personalScoreList.value) {
        if (personalScoreList.value.hasOwnProperty(key)) {
            const children = personalScoreList.value[key].children;
            if (children && children.length > 0) {
                scores.push(...children);
            }
        }
    }
    let params = {
        employee: drawerRecord.value,
        subStatus: 1, //状态
        workPlans: workPlan.value, //计划
        scores: scores //成绩
    }

    PostSubmitAssessmenteMoloyee(params).then(response => {
        if (response.code == 200) {
            message.success(response.msg)
            visible.value = false
            getData()
        } else {
            message.error(response.msg)
        }
    })
}

const returnVisible = ref<boolean>(false)
const returnReason = ref<string>("")
const handleOk = ()=>{
    if(returnReason.value.replace(/\s/g, '') == ''){
        message.error('请输入退回原因')
        return
    }
    PostauditAssessment({
        assessmentId:drawerRecord.value.id,
        empname:drawerRecord.value.empname,
        returnReason:returnReason.value,
        status:"back"
    })
    .then((response:any)=>{
        if (response.code == 200) {
            message.success(response.msg)
            visible.value  = false
            returnVisible.value = false
            getData()
        } else {
            message.error(response.msg)
        }
    })
}
</script>

<template>
    <div style="display: flex;align-items: center;justify-content: flex-end;">
        <ReloadOutlined class="operation-btn" @click="getData" />
    </div>
    <br>
    <a-table :dataSource="dataSource" :columns="columns" bordered :pagination="false">
        <template #index="{ index }">
            {{ index + 1 }}
        </template>
        <template #finalScore="{ record }">
            {{ record.assessmentGrade?record.finalScore:' - ' }}
        </template>
        <template #assessmentGrade="{ record }">
            {{ record.assessmentGrade ? record.assessmentGrade : '无' }}
        </template>
        <template #status="{ record }">
            <span>
                <a-tag color="error" v-if="record.status == -1">停用</a-tag>
                <a-tag color="error" v-if="record.status == -2 || record.status == -3">退回</a-tag>
                <a-tag color="#87d068" v-if="record.status == 1">启用</a-tag>
                <a-tag v-if="record.status == 2">部门领导审核</a-tag>
                <a-tag v-if="record.status == 3">分管领导考核</a-tag>
                <a-tag v-if="record.status == 100">处理完毕</a-tag>
            </span>
        </template>
        <template #action="{ record }">
            <span>
                <a-tag color="#2db7f5" style="cursor: pointer;" @click="showDrawer(record)">审核</a-tag>

            </span>
        </template>
    </a-table>
    <br>
    <div style="display: flex;justify-content: flex-end;">
        <a-pagination show-size-changer v-model:current="pagination.pageNum" v-model:pageSize="pagination.pageSize"
            :total="pagination.total" @showSizeChange="onShowSizeChange" />
    </div>
    <a-drawer :title="drawerRecord && drawerRecord.name + '填报月份: &nbsp;&nbsp;' + drawerRecord.reportingMonth"
        placement="right" v-model:visible="visible" width="1300" :after-visible-change="afterVisibleChange">
        <h2 style="text-align: center; font-weight: bold;">双月工作考核表</h2>
        <div style="margin-bottom: 60px;" v-if="drawerRecord">
            <div style="border-top: 1px solid #f0f0f0;">
                <div class="table-header">
                    <div style="width: 100px;">姓名</div>
                    <div style="flex: 1;">{{drawerRecord.empname}}</div>
                    <div style="flex: 1;">部门</div>
                    <div style="flex: 1;">{{drawerRecord.orgName}}</div>
                    <div style="flex: 1;">职称</div>
                    <div style="flex: 2;">
                        {{ drawerRecord.jobTitle }}
                    </div>
                    <div style="width: 100px;">岗位</div>
                    <div style="flex: 2;">
                        {{ drawerRecord.position }}
                    </div>
                    <div style="width: 100px;">职务</div>
                    <div style="flex: 1;">
                        {{ drawerRecord.duty }}
                    </div>
                </div>
                <div class="table-header">
                    <div style="background: #fafafa; width: 100%;">工作总结</div>
                </div>
                <div class="table-header">
                    <div
                        style=" height: 120px;width: 100%;justify-content: flex-start; padding: 10px;align-items:flex-start;">
                        <!-- <a-textarea placeholder="请输入工作总结" rows="4" style="height: 100px;resize: none;"
                            v-model:value="drawerRecord.workSummary" /> -->
                        {{ drawerRecord.workSummary }}
                    </div>
                </div>

                <div class="table-header">
                    <div style="width: 100px">
                        备注
                    </div>
                    <div style="flex:11;justify-content: flex-start;padding: 0 10px;">
                        <!-- <a-input placeholder="请输入备注信息" v-model:value="drawerRecord.remarks"></a-input> -->
                        {{ drawerRecord.remarks }}
                    </div>
                </div>
                <!-- <div class="table-header">
                    <div style="width: 100px">
                        附件
                    </div>
                    <div style="flex:11">
                        请上传附件
                    </div>
                </div> -->
                <div class="table-header">
                    <div style="background: #fafafa;width: 100%;position: relative;">
                        <div style="border: none;">工作计划</div>
                        <!-- <a-button style="position: absolute;right: 20px;" size="small" type="primary"
                            @click="handleAddWorkPlan">新增</a-button> -->
                    </div>
                </div>
                <div class="table-header">
                    <div style="width: 100px">序号</div>
                    <div style="flex: 4;">工作计划</div>
                    <div style="width: 140px;">拟定完成工作时间</div>
                    <div style="flex: 4;">备注</div>
                    <!-- <div style="flex: 1;">操作</div> -->
                </div>
                <div class="table-header" v-for="(item, index) in workPlan" :key="index">
                    <div style="width: 100px">{{ index + 1 }}</div>
                    <div style="flex: 4;justify-content: flex-start;">
                        <!-- <a-input placeholder="请输入工作计划" v-model:value="item.workPlanContent" /> -->
                        <div style="padding: 0 10px;">{{ item.workPlanContent }}</div>
                    </div>
                    <div style="width: 140px;padding: 0 10px;justify-content: flex-start;">
                        <!-- <a-date-picker v-model:value="item.plannedCompletionDate" /> -->
                        <div style="padding: 0 10px;">{{ item.plannedCompletionDate }}</div>
                    </div>
                    <div style="flex: 4;justify-content: flex-start;">
                        <!-- <a-input placeholder="请输入备注" v-model:value="item.remarks" /> -->
                        <div style="padding: 0 10px;">{{ item.remarks }}</div>
                    </div>
                    <!-- <div style="flex: 1;"><a-tag color="error" @click="handleDelWorkPlan(index)"
                            style="cursor: pointer;">删除</a-tag></div> -->
                </div>
                <div class="table-header" v-if="workPlan.length == 0">
                    <div style="width: 100%;color: #f00f00;">请添加工作计划</div>
                </div>
                <div class="table-header">
                    <div style="background: #fafafa;width: 100%;">工作考核自评</div>
                </div>
                <div class="table-header">
                    <div style="width: 100px">岗位职责</div>
                    <div style="flex: 11;">
                        <a-input value="5"></a-input>
                    </div>
                </div>
                <div class="table-header">
                    <div rowspan="2" style="width: 100px">考核项</div>
                    <div style="flex: 6;padding: 0 10px;">考核内容</div>
                    <div style="flex: 1;">最高得分</div>
                    <div style="flex: 1;" v-if="drawerRecord && drawerRecord.personnelType != 1">自评分</div>
                    <div style="flex: 1;">部门评分</div>
                    <div style="flex: 1;">支部评分</div>
                    <div style="flex: 1;">领导评分</div>
                </div>
                <div class="table-header" v-for="(item, index) in personalScoreList" :key="index"
                    style="display: flex;">
                    <div style="width: 100px;">{{ item.contentName }}</div>
                    <div style="flex: 1;display: flex;flex-direction: column;border-right: none;border-bottom: none;">
                        <div v-for="children in item.children" :key="children.id"
                            style="width: 1134px;display: flex;border-bottom: 1px solid #f0f0f0" class="table-chidren">
                            <div style="flex: 6;justify-content: flex-start;padding: 0 10px;">
                                <!-- {{ children &&children.content }} -->
                                <span v-html="children.content"></span>
                            </div>
                            <div style="flex: 1;">{{ children.maxScore }}</div>
                            <div style="flex: 1;" class="clear-border"
                                v-if="drawerRecord && drawerRecord.personnelType != 1">
                                <a-input-number style="height: 30px;" min="0" :max="children.maxScore"
                                    v-model:value="children.selfRating" v-if="drawerRecord.status == 1" />
                                <div v-else style="border: none;">{{ children.selfRating }}</div>
                            </div>
                            <div style="flex: 1;" class="clear-border">
                                <a-input-number style="height: 30px;" min="0" :max="children.maxScore"
                                    v-model:value="children.departmentRating" v-if="drawerRecord.status == 2" />
                                <div v-else style="border: none;">{{ children.departmentRating }}</div>
                            </div>
                            <div style="flex: 1;" class="clear-border">
                                <a-input-number style="height: 30px;" min="0" :max="children.maxScore"
                                    v-model:value="children.branchRating" v-if="drawerRecord.sumstatus == 1" />
                                <div v-else style="border: none;">{{ children.branchRating }}</div>
                            </div>
                            <div style="flex: 1;border-right: 1px solid #f0f0f0;" class="clear-border">
                                <a-input-number style="height: 30px;" min="0" :max="children.maxScore"
                                    v-model:value="children.supervisorRating"
                                    v-if="drawerRecord.status == 3 || drawerRecord.sumstatus == 2" />
                                <div v-else style="border: none;">{{ children.supervisorRating }}</div>
                            </div>
                        </div>
                    </div>

                </div>
                <div class="table-header">
                    <div style="width: 100px">合并</div>
                    <div style="flex: 6;padding: 0 10px;"></div>
                    <div style="flex: 1;">总分：{{ calculationMaxScore }}</div>
                    <div style="flex: 1;" v-if="drawerRecord && drawerRecord.personnelType != 1">总分：{{
                        calculationSelfRating
                    }}</div>
                    <div style="flex: 1;">总分：{{ calculationDepartmentRating }}</div>
                    <div style="flex: 1;">总分：{{ calculationBranchRating }}</div>
                    <div style="flex: 1;">总分：{{ calculationSupervisorRating }}</div>
                </div>
                <div class="table-header">
                    <div style="width: 100px">奖惩分数</div>
                    <div style="flex: 1;"><a-input type="text" v-model:value="drawerRecord.rewardPunishmentScore" />
                    </div>
                    <div style="width: 100px">理由</div>
                    <div style="flex: 10;"><a-input type="text" placeholder="请输入理由"
                            v-model:value="drawerRecord.rewardPunishmentReason" /></div>
                </div>
                <div class="table-header">
                    <div style="width: 100px">评定等级</div>
                    <!-- <div style="flex: 11;color: #f00f00;display: flex;justify-content: flex-start;padding-left: 20px;">{{  drawerRecord.assessmentGrade}}</div> -->
                    <div style="flex: 11;color: #f00f00;display: flex;justify-content: flex-start;padding-left: 20px;" v-if="drawerRecord.status==1 || drawerRecord.status==3">
                        <span v-if="drawerRecord.personnelType == 1 ||drawerRecord.personnelType == 2" >
                            <span v-if="calculationSupervisorRating >= 91">A</span>
                            <span v-if="calculationSupervisorRating >= 76 && calculationSupervisorRating <= 90">B</span>
                            <span v-if="calculationSupervisorRating >= 60 && calculationSupervisorRating <= 75">C</span>
                            <span v-if="calculationSupervisorRating <= 59">D</span>
                        </span>
                        <span v-if="drawerRecord.personnelType == 3">
                            <span v-if="calculationSupervisorRating >= 95">A1</span>
                            <span v-if="calculationSupervisorRating >= 91 && calculationSupervisorRating <= 94">A2</span>
                            <span v-if="calculationSupervisorRating >= 86 && calculationSupervisorRating <= 90">B1</span>
                            <span v-if="calculationSupervisorRating >= 81 && calculationSupervisorRating <= 85">B2</span>
                            <span v-if="calculationSupervisorRating >= 76 && calculationSupervisorRating <= 81">B3</span>
                            <span v-if="calculationSupervisorRating >= 71 && calculationSupervisorRating <= 75">C1</span>
                            <span v-if="calculationSupervisorRating >= 60 && calculationSupervisorRating <= 70">C2</span>
                            <span v-if="calculationSupervisorRating <= 59"></span>
                        </span>
                    </div>
                    <div style="flex: 11;color: #f00f00;display: flex;justify-content: flex-start;padding-left: 20px;" v-if="drawerRecord.status==2">
                        <span v-if="drawerRecord.personnelType == 1">
                            <span v-if="calculationDepartmentRating >= 91">A</span>
                            <span v-if="calculationDepartmentRating >= 76 && calculationDepartmentRating <= 90">B</span>
                            <span v-if="calculationDepartmentRating >= 60 && calculationDepartmentRating <= 75">C</span>
                            <span v-if="calculationDepartmentRating <= 59">D</span>
                        </span>
                        <span v-else>
                            <span v-if="calculationDepartmentRating >= 95">A1</span>
                            <span v-if="calculationDepartmentRating >= 91 && calculationDepartmentRating <= 94">A2</span>
                            <span v-if="calculationDepartmentRating >= 86 && calculationDepartmentRating <= 90">B1</span>
                            <span v-if="calculationDepartmentRating >= 81 && calculationDepartmentRating <= 85">B2</span>
                            <span v-if="calculationDepartmentRating >= 76 && calculationDepartmentRating <= 81">B3</span>
                            <span v-if="calculationDepartmentRating >= 71 && calculationDepartmentRating <= 75">C1</span>
                            <span v-if="calculationDepartmentRating >= 60 && calculationDepartmentRating <= 70">C2</span>
                            <span v-if="calculationDepartmentRating <= 59"></span>
                        </span>
                    </div>
                  
                </div>
            </div>
        </div>
        <div :style="{
            position: 'absolute',
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e8e8e8',
            padding: '10px 16px',
            textAlign: 'right',
            left: 0,
            background: '#fff',
            borderRadius: '0 0 4px 4px',
        }">
            <a-button style="margin-right: 8px" @click="() => visible = false">关闭</a-button>
            <a-button type="primary" danger style="margin-right: 8px" @click="()=>returnVisible = true">退回</a-button>
            <!-- <a-button type="primary" @click="handleSaveDraft" style="margin-right: 8px">保存草稿</a-button> -->
            <a-button type="primary" @click="handleSubmit">提交</a-button>
        </div>
    </a-drawer>
    <a-modal v-model:visible="returnVisible" title="退回" @ok="handleOk">
        <a-textarea v-model:value="returnReason" placeholder="请输入退回原因" :rows="4" />
    </a-modal>
</template>

<style scoped>
.table-header {
    display: flex;
    width: 1235px;
    /* align-items: center; */
    /* border-top: 1px solid #f0f0f0; */
    border-left: 1px solid #f0f0f0;
}

.table-header>div {
    border-right: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
    /* flex: 1; */
    /* height: 50px; */
    min-height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.ant-input {
    border: none !important;
}

.ant-input:focus {
    border: none !important;
    box-shadow: none !important;
}

.clear-border {
    align-items: normal;
}

.clear-border div {
    border: 1px solid #d9d9d9;
    min-height: 30px;

}

.table-chidren>div {
    border-bottom: none;
    line-height: 2;
    border-right: 1px solid #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px 0;
}

.operation-btn {
    border: 1px solid #F2F3F5;
    width: 35px;
    height: 35px;
    display: block;
    border-radius: 35px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    margin-left: 10px;
    font-weight: 700;
}

.operation-btn:hover {
    background: #f2f3f5;
    color: #1677ff;
}
</style>
